import store from '@/store/index.js'

/**
 * 相当于提供给H5的一个接口
 */
export default class Hybrid {
	constructor(webView) {
		this.webView = webView
	}

	localStorage = {
		setItem: (key, val) => {
			this.webView.evalJs('localStorage.setItem', key, val)
		},
		removeItem: key => {
			this.webView.evalJs('localStorage.removeItem', key)
		},
		clear: () => {
			this.webView.evalJs('localStorage.clear')
		}
	}

	/**
	 * 提供给H5设置头部组件的一个接口
	 * @param {Object} fn
	 */
	setHeader(fn) {
		this.webView.registerHandler('setHeader', (data, callback) => {
			fn && fn(data, callback)
		});
	}

	/**
	 * 登录
	 */
	login() {
		this.webView.registerHandler('login', async (data, callback) => {
			if (store.state.isLogin) {
				return uni.showToast({
					title: '请勿重复登录',
					icon: 'none'
				})
			}

			uni.showLoading({
				title: '正在登录'
			})

			let res
			try {
				res = await store.dispatch('login', data)
				// 把登录态注入到H5中的localStorage中
				res.code === 0 && this.localStorage.setItem('token', res.data)
			} catch (e) {
				res = e
			}

			uni.hideLoading()
			callback(res)
		})
	}

	logout() {
		this.webView.registerHandler('logout', async (data, callback) => {
			let res
			try {
				res = await store.dispatch('logout', data)
				res.code === 0 && this.localStorage.removeItem('token')
			} catch (e) {
				res = e
			}

			uni.showToast({
				title: '登出成功',
				icon: 'none'
			})

			callback(res)
		})
	}
}
